package com.rickpan.controller;

import com.rickpan.dto.share.CreateShareRequest;
import com.rickpan.dto.share.UpdateShareRequest;
import com.rickpan.dto.share.ShareResponse;
import com.rickpan.dto.share.ShareAccessLogResponse;
import com.rickpan.dto.common.ApiResponse;
import com.rickpan.service.FileShareService;
import com.rickpan.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.time.LocalDateTime;

/**
 * 文件分享管理控制器
 * 
 * @author RickPan Team
 * @since 2025-01-05
 */
@RestController
@RequestMapping("/api/shares")
public class FileShareController {

    private static final Logger log = LoggerFactory.getLogger(FileShareController.class);

    @Autowired
    private FileShareService fileShareService;

    /**
     * 创建文件分享
     * POST /api/shares
     */
    @PostMapping
    public ResponseEntity<ApiResponse<ShareResponse>> createShare(@Valid @RequestBody CreateShareRequest request) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            log.info("用户 {} 创建分享: fileId={}", userId, request.getFileId());

            ShareResponse response = fileShareService.createShare(userId, request);
            
            return ResponseEntity.ok(ApiResponse.success("分享创建成功", response));
            
        } catch (Exception e) {
            log.error("创建分享失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("创建分享失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户分享列表
     * GET /api/shares?page=0&size=10&sort=createdAt,desc&keyword=&status=&startDate=&endDate=
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<ShareResponse>>> getUserShares(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String type) {

        try {
            Long userId = SecurityUtils.getCurrentUserId();
            log.debug("获取用户分享列表: userId={}, page={}, size={}, keyword={}, status={}",
                    userId, page, size, keyword, status);

            // 创建分页和排序参数
            Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
            Pageable pageable = PageRequest.of(page, size, sort);

            // 创建筛选参数
            ShareFilterParams filterParams = new ShareFilterParams();
            filterParams.setKeyword(keyword);
            filterParams.setStatus(status);
            filterParams.setStartDate(startDate);
            filterParams.setEndDate(endDate);
            filterParams.setType(type);

            Page<ShareResponse> shares = fileShareService.getUserSharesWithFilter(userId, pageable, filterParams);

            return ResponseEntity.ok(ApiResponse.success(shares));

        } catch (Exception e) {
            log.error("获取分享列表失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取分享列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取分享详情
     * GET /api/shares/{shareId}
     */
    @GetMapping("/{shareId}")
    public ResponseEntity<ApiResponse<ShareResponse>> getShareDetail(@PathVariable Long shareId) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            log.debug("获取分享详情: userId={}, shareId={}", userId, shareId);

            // 这里可以添加获取单个分享详情的逻辑
            // 暂时返回错误，因为我们主要通过shareCode访问
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("请使用分享码访问分享"));
            
        } catch (Exception e) {
            log.error("获取分享详情失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取分享详情失败: " + e.getMessage()));
        }
    }

    /**
     * 更新分享设置
     * PUT /api/shares/{shareId}
     */
    @PutMapping("/{shareId}")
    public ResponseEntity<ApiResponse<ShareResponse>> updateShare(
            @PathVariable Long shareId,
            @Valid @RequestBody UpdateShareRequest request) {
        
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            log.info("更新分享设置: userId={}, shareId={}", userId, shareId);

            ShareResponse response = fileShareService.updateShare(userId, shareId, request);
            
            return ResponseEntity.ok(ApiResponse.success("分享设置更新成功", response));
            
        } catch (Exception e) {
            log.error("更新分享设置失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("更新分享设置失败: " + e.getMessage()));
        }
    }

    /**
     * 删除分享
     * DELETE /api/shares/{shareId}
     */
    @DeleteMapping("/{shareId}")
    public ResponseEntity<ApiResponse<Void>> deleteShare(@PathVariable Long shareId) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            log.info("删除分享: userId={}, shareId={}", userId, shareId);

            fileShareService.deleteShare(userId, shareId);
            
            return ResponseEntity.ok(ApiResponse.success("分享删除成功"));
            
        } catch (Exception e) {
            log.error("删除分享失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("删除分享失败: " + e.getMessage()));
        }
    }

    /**
     * 获取分享统计信息
     * GET /api/shares/stats
     */
    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<ShareStatsResponse>> getShareStats() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            log.debug("获取分享统计: userId={}", userId);

            ShareStatsResponse stats = fileShareService.getShareStats(userId);

            return ResponseEntity.ok(ApiResponse.success(stats));

        } catch (Exception e) {
            log.error("获取分享统计失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取分享统计失败: " + e.getMessage()));
        }
    }

    /**
     * 禁用分享
     * PUT /api/shares/{shareId}/disable
     */
    @PutMapping("/{shareId}/disable")
    public ResponseEntity<ApiResponse<Void>> disableShare(@PathVariable Long shareId) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            log.info("禁用分享: userId={}, shareId={}", userId, shareId);

            fileShareService.disableShare(userId, shareId);

            return ResponseEntity.ok(ApiResponse.success("分享已禁用"));

        } catch (Exception e) {
            log.error("禁用分享失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("禁用分享失败: " + e.getMessage()));
        }
    }

    /**
     * 启用分享
     * PUT /api/shares/{shareId}/enable
     */
    @PutMapping("/{shareId}/enable")
    public ResponseEntity<ApiResponse<Void>> enableShare(@PathVariable Long shareId) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            log.info("启用分享: userId={}, shareId={}", userId, shareId);

            fileShareService.enableShare(userId, shareId);

            return ResponseEntity.ok(ApiResponse.success("分享已启用"));

        } catch (Exception e) {
            log.error("启用分享失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("启用分享失败: " + e.getMessage()));
        }
    }

    /**
     * 获取分享访问日志
     * GET /api/shares/{shareId}/logs
     */
    @GetMapping("/{shareId}/logs")
    public ResponseEntity<ApiResponse<Page<ShareAccessLogResponse>>> getShareAccessLogs(
            @PathVariable Long shareId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            log.debug("获取分享访问日志: userId={}, shareId={}", userId, shareId);

            // 创建分页参数
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "accessTime"));

            Page<ShareAccessLogResponse> logs = fileShareService.getShareAccessLogs(userId, shareId, pageable);

            return ResponseEntity.ok(ApiResponse.success(logs));

        } catch (Exception e) {
            log.error("获取分享访问日志失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取分享访问日志失败: " + e.getMessage()));
        }
    }

    /**
     * 分享统计响应DTO
     */
    public static class ShareStatsResponse {
        private Long totalShares;
        private Long activeShares;
        private Long expiredShares;
        private Long totalAccess;
        private Long todayAccess;
        private Long downloadCount;
        private Long previewCount;

        public ShareStatsResponse() {}

        public ShareStatsResponse(Long totalShares, Long activeShares, Long expiredShares,
                                Long totalAccess, Long todayAccess, Long downloadCount, Long previewCount) {
            this.totalShares = totalShares;
            this.activeShares = activeShares;
            this.expiredShares = expiredShares;
            this.totalAccess = totalAccess;
            this.todayAccess = todayAccess;
            this.downloadCount = downloadCount;
            this.previewCount = previewCount;
        }

        // Getters and Setters
        public Long getTotalShares() { return totalShares; }
        public void setTotalShares(Long totalShares) { this.totalShares = totalShares; }

        public Long getActiveShares() { return activeShares; }
        public void setActiveShares(Long activeShares) { this.activeShares = activeShares; }

        public Long getExpiredShares() { return expiredShares; }
        public void setExpiredShares(Long expiredShares) { this.expiredShares = expiredShares; }

        public Long getTotalAccess() { return totalAccess; }
        public void setTotalAccess(Long totalAccess) { this.totalAccess = totalAccess; }

        public Long getTodayAccess() { return todayAccess; }
        public void setTodayAccess(Long todayAccess) { this.todayAccess = todayAccess; }

        public Long getDownloadCount() { return downloadCount; }
        public void setDownloadCount(Long downloadCount) { this.downloadCount = downloadCount; }

        public Long getPreviewCount() { return previewCount; }
        public void setPreviewCount(Long previewCount) { this.previewCount = previewCount; }
    }

    /**
     * 分享筛选参数DTO
     */
    public static class ShareFilterParams {
        private String keyword;
        private String status;
        private String startDate;
        private String endDate;
        private String type;

        // Getters and Setters
        public String getKeyword() { return keyword; }
        public void setKeyword(String keyword) { this.keyword = keyword; }

        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }

        public String getStartDate() { return startDate; }
        public void setStartDate(String startDate) { this.startDate = startDate; }

        public String getEndDate() { return endDate; }
        public void setEndDate(String endDate) { this.endDate = endDate; }

        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
    }


}
